package cn.cstech.aijia.sns.weixin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import cn.cstech.aijia.R;
import cn.cstech.aijia.sns.Constants;
import cn.cstech.aijia.ui.base.utils.DialogUtil;
import cn.cstech.aijia.ui.base.utils.LoadingDialog;

/**
 * @author evan zhanghui451@jk.cn 14-9-16
 * @version 0.1
 */
public abstract class BaseWXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "BaseWXEntryActivity";
    private IWXAPI iwxapi;
    private String weixinAppID;
    //private String weixinAppSecret;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        weixinAppID = Constants.WEIXIN_APP_ID;
        //weixinAppSecret = getMetaData(this, "WEIXIN_APPSECRET");
        //通过WXAPIFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(this, weixinAppID, false);
        iwxapi.registerApp(weixinAppID);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        iwxapi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        int result = 0;
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = R.string.weixin_errcode_success;
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.weixin_errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.weixin_errcode_deny;
                break;
            default:
                result = R.string.weixin_errcode_unknown;
                break;
        }
        Log.d("WeixinLogin", getString(result));
        if (BaseResp.ErrCode.ERR_OK != baseResp.errCode) {
            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
            finish();
        } else {
            //获得AccessToken并登录会员中心
            SendAuth.Resp resp = ((SendAuth.Resp) baseResp);
            String code = resp.code;
//            Toast.makeText(this, "Code:" + code + ",openid:" + resp.openId + ",transaction:" +resp.transaction 
//            		+ ",state:" + resp.state + ",url:" + resp.url, Toast.LENGTH_LONG).show();
            showLoadingDialog(getString(R.string.dlg_msg_logining));
//            NetManager.getInstance(this).doWeixinLogin(code,
//                    new OnLoginListener() {
//                        @Override
//                        public void onComplete(boolean isOK, int errorCode, String errorMsg) {
//                            if (isOK) {
//                                Log.d(TAG, "Send weixin access token ok");
////                                Toast.makeText(BaseWXEntryActivity.this, "Send weixin access token ok", Toast.LENGTH_LONG).show();
//                                Intent intent = new Intent(LoginActivity.mEnterAppAction);
//                                ((UserCenterApplication)getApplication()).exitAllActivity();
//                                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                intent.putExtra(Preference.ACTION, Preference.ACTION_FINISH);
//                                startActivity(intent);
//                                finish();
//                            } else {
//                                Log.e(TAG, "Send weixin access token fail, errCode:" + errorCode + ", errMsg:" + errorMsg);
////                                Toast.makeText(BaseWXEntryActivity.this, "Send weixin access token fail, errCode:" +
////                                        errorCode + ", errMsg:" + errorMsg, Toast.LENGTH_LONG).show();
//                                LocalUtils.showToast(BaseWXEntryActivity.this, StringUtil
//    									.handlerErrorCode(BaseWXEntryActivity.this, errorCode));
//                                finish();
//                            }
//                            hideLoadingDialog();
//                        }
//
//                        @Override
//                        public void onInernError(int errorCode, String errorMessage) {
//                            Log.d(TAG, "send weixin access token fail");
//                            LocalUtils.showToast(BaseWXEntryActivity.this, StringUtil
//									.handlerErrorCode(BaseWXEntryActivity.this, errorCode));
//                            finish();
//                            hideLoadingDialog();
//                        }
//                    });
        }
    }

    //获得配置在AndroidManifest.xml文件中的微信和QQ登录的相关配置
    private String getMetaData(Context context, String name) {
        try {
            ApplicationInfo app = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = app.metaData;
            return String.valueOf(bundle.getString(name));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private LoadingDialog loadingDialog;
	protected void showLoadingDialog(String msg) {
		if (loadingDialog == null) {
			loadingDialog = DialogUtil.showLoadingDialog(this, msg, true);
		}
		if (!TextUtils.isEmpty(msg)) {
			loadingDialog.setDlgMessage(msg);
		}
		if (!loadingDialog.isShowing()) {
			loadingDialog.show();
		}
	}

	protected void hideLoadingDialog() {
		if (loadingDialog != null && loadingDialog.isShowing()) {
			loadingDialog.dismiss();
		}
	}
}
